from azure.devops.connection import Connection
from msrest.authentication import BasicAuthentication
from azure.devops.v6_0.git.models import GitQueryCommitsCriteria, GitVersionDescriptor
# import git

# 设置Azure DevOps的组织和项目信息
organization_url = 'https://dev.azure.com/HKITDevOps'
project_name = 'HKWebApp'
personal_access_token = 'rohvxi4cveemyk2ttapc5whjn22ohjfmeabdds7xh4nn7ls7uctq'
# 源码仓库ID
repository_id = '75ae6a7f-d134-4337-9133-99d4176792a8'  # 在Azure DevOps中找到您的仓库ID


# 创建连接
credentials = BasicAuthentication('', personal_access_token)
connection = Connection(base_url=organization_url, creds=credentials)

# 获取Git客户端
git_client = connection.clients.get_git_client()

"""
# 使用Git客户端获取特定Git仓库的refs，然后筛选出tags
# refs 是指向git的一个引用
refs = git_client.get_refs(project=project_name, repository_id=repository_id, filter='tags', filter_contains='2.5')
for tag in refs.value:
    # object_id 就是commit 的sha（也就是网页看到的id）
    print(tag.object_id, ":", tag.name)
"""

# 创建查询条件
criteria = GitQueryCommitsCriteria()
criteria.from_date = '6/14/2024 12:00:00'
criteria.to_date = '7/14/2024 12:00:00'

# 需要使用指定的类型才能按版本号查询
version_descriptor = GitVersionDescriptor(
    version = 'V2.53.1-sale',
    version_type = "branch"  # 使用 branch 关键字
)
criteria.item_version = version_descriptor
criteria.includeUserImageUrl = False
criteria.includeLinks = False
criteria.top = 20

# 获取特定分支的提交记录
commit_list = git_client.get_commits(repository_id=repository_id, search_criteria=criteria)


# 遍历提交并提取信息
for commit in commit_list:
    print(f"Commit ID: {commit.commit_id}")
    print(f"Author: {commit.author.name}")
    print(f"Committer: {commit.committer.name}")
    print(f"Comment: {commit.comment}")
    print(f"Comment Truncated: {commit.comment_truncated}")
    print(f"Parent IDs: {commit.parents}")
    # print(f"Tree ID: {commit.commit_details.tree_id}")
    # print(f"URL: {commit.url}")
    # 如果有变更计数信息
    if commit.change_counts:
        print(f"Change Counts: {commit.change_counts}")
    print("-" * 40)  # 分隔线

exit(0)
# 遍历提交记录并打印详细信息
for commit in commit_list:
    print(f"Commit ID: {commit.commit_id}")
    print(f"Committed by: {commit.author.name}")
    print(f"Commit Date: {commit.committer.date}")
    print(f"Commit Message: {commit.comment}")
    # print(commit)

    # 获取提交的标签（如果存在）
    # help(git_client)



    print("-" * 40)  # 分隔线

exit(0)
for ref in refs:
    if ref.name.startswith('refs/heads/'):  # 分支
        commits = git_client.get_commits(repo_id, ref.name)
        for commit in commits:
            print(f"Branch: {ref.name}, Commit ID: {commit.commit_id}, Commit Message: {commit.comment}")
""""
# 2. 新建源码分支并提交
new_branch_name = 'new-branch'
source_branch_name = 'refs/heads/master'  # 假设从master分支创建新分支

# 克隆仓库
repo_url = f"https://{personal_access_token}@dev.azure.com/{organization_url.split('/')[-1]}/{project_name}/_git/{repo_id}"
repo = git.Repo.clone_from(repo_url, './repo')

# 创建并切换到新分支
repo.git.checkout('-b', new_branch_name)

# 假设我们添加一个新文件并提交
with open('./repo/new-file.txt', 'w') as f:
    f.write('Hello, Azure DevOps!')

repo.index.add(['new-file.txt'])
repo.index.commit('Add new file')

# 推送新分支到远程仓库
repo.git.push('origin', new_branch_name)
"""
exit(0)
# 获取Work item客户端
work_item_client = connection.clients.get_work_item_tracking_client()

# 获取Work items的信息
work_item_ids = [126337, 126338, 126339]  # 假设我们要获取ID为1, 2, 3的Work items
work_items = work_item_client.get_work_items(ids=work_item_ids)

# 打印Work items的信息
for work_item in work_items:
    print(f"Work Item ID: {work_item.id}, Title: {work_item.fields['System.Title']}")



exit(0)
# 示例代码
# 获取项目中的所有仓库
# repos = git_client.get_repositories(project_name)

# 打印每个仓库的名称和ID
# for repo in repos:
    # print(f"Repo Name: {repo.name}, Repo ID: {repo.id}")